package com.example.HelloSpace.ui;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.example.HelloSpace.MainActivity;
import com.example.HelloSpace.R;
import com.example.HelloSpace.models.MissionInfoModel;
import com.example.HelloSpace.ui.mission_details.MissionDetailsFragment;
import com.example.HelloSpace.utils.MyApp;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.android.material.textview.MaterialTextView;

import java.util.Objects;

public class MissionSubscribedView extends FrameLayout {
    private String URL;
    private CardView cardView;
    private ShapeableImageView image;
    private View fadeOverlay;

    //任务信息
    private MissionInfoModel missionInfoModel;
    private String imageUrl;
    private MaterialTextView countDown;
    private MaterialTextView missionName;
    private boolean isCountingDown = false;

    private MaterialTextView statusText;
    private CardView statusCard;

    private int isAnimating = 0; // 动画状态标志
    private boolean isExpanded = false;
    private boolean isPressed;
    //    private MissionDetailsViewModel model;
//    private View sharedElement;


    public MissionSubscribedView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public MissionSubscribedView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MissionSubscribedView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }



    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.view_mission_subscribed, this, true);

//        post(()->{
//            if (getContext() instanceof Activity && !((Activity) getContext()).isFinishing()) {
//
//                ViewUtils.resizeViewByWidth(context, this, 0.91f, 0.09f);
//                cardView.setOnTouchListener((v, event) -> {
//                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
//                        handlePress();
//                    } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
//                        handleRelease();
//                    }
//                    return true;
//                });
//                // 设置渐变效果
//                fadeOverlay.post(() -> applyFadeEffect(fadeOverlay, this,0.4f, 0.6f));
//
//            }
//        });
        URL= MyApp.getSERVER_URL();
        cardView = findViewById(R.id.card_view);
        image = findViewById(R.id.imageView);
        fadeOverlay = findViewById(R.id.fadeOverlay);
        statusText = findViewById(R.id.state_tag_text);
        statusCard = findViewById(R.id.state_tag_card);
        countDown= findViewById(R.id.countdown);
        missionName = findViewById(R.id.mission);
    }


    public void setMissionName(String missionName) {
        this.missionName.setText(missionName);
    }
    public void setMissionImage(String imageUrl){
        Glide.with(getContext())
                .load(URL+imageUrl)
                .into(image);
    }

    public void setCountDown(String countDown) {
        this.countDown.setText(countDown);
    }

    public void setStatusTag(String status){
        statusText.setText(status);
        if(Objects.equals(status, "成功")){
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_success));
        }
        else if(Objects.equals(status, "失败")){
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_failure));
        }
        else if(Objects.equals(status, "异常")){
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_anomaly));
        }
        else if(Objects.equals(status, "预计")){
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_scheduled));
        }
        else{
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_cancelled_or_custom));
        }
    }

    private void applyFadeEffect(View overlay, View view,float startRatio, float endRatio) {
        int width = overlay.getWidth();
        int height = view.getHeight();
        Log.d("applyFadeEffect", "width=" + width + ", height=" + height);

        if (width > 0 && height > 0) {
            // 定义渐变颜色
            int[] colors = new int[]{0x00FFFFFF, 0xFFFFFFFF}; // 透明 -> 半透明黑色

            // 设置渐变起点和终点
            float angleInRadians = (float) Math.toRadians(-40); // 负值表示逆时针旋转
            float startX = startRatio * width;
            float startY = 0;
            float endX = endRatio * width;
            float endY = 0;

            // 计算旋转后的起点和终点
            float rotatedStartX = startX + height * (float) Math.sin(angleInRadians);
            float rotatedStartY = startY + height * (float) Math.cos(angleInRadians);
            float rotatedEndX = endX - height * (float) Math.sin(angleInRadians);
            float rotatedEndY = endY + height * (float) Math.cos(angleInRadians);

            // 创建一个带有旋转的线性渐变
            LinearGradient gradient = new LinearGradient(
                    rotatedStartX, rotatedStartY, rotatedEndX, rotatedEndY,
                    colors, null, Shader.TileMode.CLAMP
            );

            // 创建 Paint 并设置其 Shader
            Paint paint = new Paint();
            paint.setShader(gradient);
            // 将渐变应用到 View 的背景
            Bitmap bitmap = createBitmapWithShader(paint, width, height);
            Drawable drawable = new BitmapDrawable(overlay.getResources(), bitmap);
            overlay.setBackground(drawable);
        }
    }

    private Bitmap createBitmapWithShader(Paint paint, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawRect(0, 0, width, height, paint);
        return bitmap;
    }

    private void handlePress() {
        isPressed = true;
        if (!isExpanded && isAnimating==0) {
            isAnimating = 1; // 开始动画
            cardView.animate().scaleX(0.95f).scaleY(0.95f)
                    .setDuration(100)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            // 动画结束时，允许按钮释放
                            cardView.setEnabled(true);
                            isAnimating = 2;
                            if(!isPressed&&!isExpanded){
                                isExpanded = true;
                                cardView.animate().scaleX(1f).scaleY(1f)
                                        .setDuration(100)
                                        .setListener(new AnimatorListenerAdapter() {
                                            @Override
                                            public void onAnimationEnd(Animator animation) {
                                                expandToMissionDetails(); // 打开新页面
                                                isAnimating = 0; // 动画结束
                                            }
                                        })
                                        .start();
                            }
                        }
                    })
                    .start();
        }
    }

    private void handleRelease() {
        isPressed = false;
        if (!isExpanded && isAnimating==2) {
            cardView.animate().scaleX(1f).scaleY(1f)
                    .setDuration(100)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            isAnimating = 0; // 动画结束
                        }
                    })
                    .start();
        }
    }

    private void expandToMissionDetails() {

        // 启动 MissionDetailsFragment
        MissionDetailsFragment detailsFragment = new MissionDetailsFragment();

        // 创建一个新的 Bundle 来传递参数（如果需要）
        Bundle fragmentArgs = new Bundle();
        // 需要传递的参数
        fragmentArgs.putInt("missionID",missionInfoModel.getId());
        fragmentArgs.putString("missionName",missionInfoModel.getMissionName());
        detailsFragment.setArguments(fragmentArgs);

        // 确保 Context 是一个 Activity，并且是一个 MainActivity 实例
        if (getContext() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getContext();
            activity.getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.main_frame_layout, detailsFragment)
                    .addToBackStack(null) // 添加到回退栈
                    .commit();
        } else {
            throw new IllegalStateException("The context is not an instance of MainActivity");
        }
        isExpanded = false;
    }
}
